package org.ascollada.io
{
	import flash.display.Bitmap;
	import flash.errors.IOError;
	import flash.net.URLRequest;
	
	import org.libspark.thread.Thread;
	import org.libspark.thread.threads.display.LoaderThread;
	import org.libspark.thread.threads.net.URLLoaderThread;
	import org.libspark.thread.utils.Executor;
	import org.libspark.thread.utils.ParallelExecutor;
	
	public class DaeFileLoaderThread extends Thread
	{
		private var _loader :URLLoaderThread;
		
		private var _fileLoaders :Executor;
		
		private var _urls :Array;
		
		/**
		 * 
		 */ 
		public function DaeFileLoaderThread()
		{
			_urls = new Array();
		}
		
		/**
		 * 
		 */ 
		public function addFile(url:String):void
		{
		//	if(_urls.indexOf(url) == -1)
				_urls.push(url);
		}
		
		/**
		 * 
		 */ 
		protected override function run():void
		{
			if(!_urls || !_urls.length)
			{
				trace("Thread: nothing to do!");
			}
			
			_fileLoaders = new ParallelExecutor();
			
			for each(var url:String in _urls)
			{
				_fileLoaders.addThread(new LoaderThread(new URLRequest(url)));
			}
			
			_fileLoaders.start();
			_fileLoaders.join();
			
			next(executeComplete);
			
			error(IOError, errorHandler);
			error(SecurityError, errorHandler);
		}
		
		protected override function finalize():void
		{
			trace("Thread done");	
			
			_fileLoaders = null;
			_urls = new Array();
		}
		
		private function executeComplete():void
		{
			//debug
			trace("MainThread XML Complete Loading.");
			
			for(var i:int = 0; i < _urls.length; i++)
			{
				var thread :LoaderThread = _fileLoaders.getThreadAt(i) as LoaderThread;
				
				trace((thread.loader.content is Bitmap));
			}
		}
		
		/**
		 * 
		 */ 
		private function errorHandler(e:IOError, t:Thread):void
		{
			//debug
			trace("MainThread Error.");

			//例外を出力して終了
			trace(e.getStackTrace());

			//例外ハンドラから終了する
			next(null);
		}
	}
}